package com.ccqlk.basemainapp.mas;

import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.FastExcelFactory;
import cn.idev.excel.support.ExcelTypeEnum;
import cn.idev.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class 云MAS批量创建导出任务_本地数据 {
    private static final String DUAN_KOU = "10691155";
    private static final String ENTERPRISE_NAME = "重庆医科大学附属第一医院" + DUAN_KOU;

    private static final String BASE_FILE_URL = "C:/Users/13525/Documents";
    private static final String IP_REGEX = "\\b((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\b";
    private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX);
    private static final List<String> PHONE_MAY_BE = Arrays.asList("联系","致电","回电","号码","拨号","来电","拨打","电话","咨询","023-","023");



    public static void main(String[] args) {

        // 创文件夹，初始写入对象
        File oldDataFileDir = new File(BASE_FILE_URL + File.separator + ENTERPRISE_NAME + File.separator + "mas10086原始文件");

        Set<String> allHttp = new HashSet<>();
        Set<String> allPhone = new HashSet<>();

        // 写链接excel
        ExcelWriter excelWriterHttp = FastExcelFactory
                .write(BASE_FILE_URL + File.separator + ENTERPRISE_NAME +  File.separator + "包含链接的所有短信.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .autoCloseStream(Boolean.FALSE)
                .build();
        WriteSheet writeSheetHttp = new WriteSheet();
        writeSheetHttp.setSheetNo(1);

        // 写号码excel
        ExcelWriter excelWriterPhone = FastExcelFactory
                .write(BASE_FILE_URL + File.separator + ENTERPRISE_NAME + File.separator + "包含号码的所有短信.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .autoCloseStream(Boolean.FALSE)
                .build();
        WriteSheet writeSheetPhone = new WriteSheet();
        writeSheetPhone.setSheetNo(1);


        // 每个任务都下载文件
        File[] files = oldDataFileDir.listFiles();
        if(files !=null ){
            for (File file : files) {
                downloadFileAndAnalyzeWrite(file,excelWriterHttp,writeSheetHttp,excelWriterPhone,writeSheetPhone,allHttp,allPhone);
            }
        }

        // 单独写链接
        List<List<String>> allHttpDataList = allHttp
                .stream()
                .map(data -> {
                    List<String> dataList = new ArrayList<>();
                    dataList.add(data);
                    return dataList;
                })
                .toList();
        FastExcelFactory
                .write(BASE_FILE_URL + File.separator + ENTERPRISE_NAME + File.separator + "所有的链接.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(0)
                .sheetName("链接")
                .doWrite(allHttpDataList);


        // 单独写号码
        List<List<String>> allPhoneDataList = allPhone
                .stream()
                .map(data -> {
                    List<String> dataList = new ArrayList<>();
                    dataList.add(data);
                    return dataList;
                })
                .toList();
        FastExcelFactory
                .write(BASE_FILE_URL + File.separator + ENTERPRISE_NAME + File.separator + "所有的电话.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(0)
                .sheetName("电话")
                .doWrite(allPhoneDataList);


        excelWriterHttp.finish();
        excelWriterPhone.finish();
    }

    private static void downloadFileAndAnalyzeWrite(File file,
                                                    ExcelWriter excelWriterHttp,
                                                    WriteSheet writeSheetHttp,
                                                    ExcelWriter excelWriterPhone,
                                                    WriteSheet writeSheetPhone,
                                                    Set<String> allHttp,
                                                    Set<String> allPhone) {
        // 记录所有的匹配链接和短信
        List<LinkedHashMap<Integer,String>> matchHttpData = new ArrayList<>();
        List<LinkedHashMap<Integer,String>> matchPhoneData = new ArrayList<>();

        // 读excel
        List<LinkedHashMap<Integer,String>> dataList = FastExcel.read(file).doReadAllSync();

        // 分组
        Map<String, List<LinkedHashMap<Integer, String>>> groupMap = dataList.stream().collect(Collectors.groupingBy(data -> {
            String content = data.get(3);
            content = content.substring(0,content.indexOf(")") + 1);
            if(content.startsWith("(") && content.endsWith(")")){
                return data.get(0) + data.get(1);
            } else {
                return data.get(0) + data.get(1) + UUID.randomUUID();
            }
        }));

        // 匹配
        groupMap.forEach((key, value) -> {
            String content;
            // 超过1条 需要拼接
            if(value.size() > 1){
                StringBuilder sb = new StringBuilder();
                value
                        .stream()
                        .sorted(Comparator.comparing(data -> {
                            char charAt = data.get(3).charAt(1);
                            String string = String.valueOf(charAt);
                            try {
                                return Integer.parseInt(string);
                            } catch (Exception e) {
                                System.out.println(key);
                                System.out.println(value);
                                System.out.println(data.get(3));
                                throw e;
                            }
                        }))
                        .forEach(data -> {
                            String contentThis = data.get(3);
                            String finalData = contentThis.substring(contentThis.indexOf(")") + 1);
                            sb.append(finalData);
                        });
                content = sb.toString();
            } else {
                content = value.getFirst().get(3);
            }

            // 包含网站，网站可以直接提取，所以放进集合
            boolean containsHttp = false;
            Matcher ipMatcher = IP_PATTERN.matcher(content);
            while (ipMatcher.find()) {
                containsHttp = true;
                allHttp.add(ipMatcher.group()); // 去掉尾部的点
            }
            if(content.contains("//")){
                containsHttp = true;
                int index = 0;
                while ((index = content.indexOf("//", index)) != -1) {
                    int start = Math.max(0,index - 10);
                    int end = Math.min(start + 50, content.length());
                    String extracted = content.substring(start, end);
                    allHttp.add(extracted);
                    index = start + 11; // 防止死循环，继续向后查找
                }
            }

            if(containsHttp){
                value.getFirst().put(3,content);
                matchHttpData.add(value.getFirst());
            }

            if((content.contains("联系") ||
                    content.startsWith("023-") ||
                    content.contains("致电") ||
                    content.contains("回电") ||
                    content.contains("号码") ||
                    content.contains("拨号") ||
                    content.contains("来电") ||
                    content.contains("拨打") ||
                    content.contains("电话")) && !content.contains("票据号码")){
                value.getFirst().put(3,content);
                matchPhoneData.add(value.getFirst());

                // 提取号码
                for (String mainWord : PHONE_MAY_BE) {
                    int index = 0;
                    while ((index = content.indexOf(mainWord, index)) != -1) {
                        int start = Math.max(0,index - 10);
                        int end = Math.min(start + 30, content.length());
                        String extracted = content.substring(start, end);
                        if(!extracted.contains("票据号码")){
                            allPhone.add(extracted);
                        }
                        index = start + 11; // 防止死循环，继续向后查找
                    }
                }

            }
        });

        // 写了不flush,续写
        excelWriterHttp.write(matchHttpData,writeSheetHttp);
        excelWriterPhone.write(matchPhoneData,writeSheetPhone);
    }
}
